package com.comdo.newup_loan.module.repayment_action;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.comdo.newup_loan.R;
import com.comdo.newup_loan.base.BaseActivity;
import com.comdo.newup_loan.comom.Config;
import com.comdo.newup_loan.model.ToXuDaiApply;
import com.comdo.newup_loan.model.UpLoadBean;
import com.comdo.newup_loan.module.recharge.MineTopUpActivity;
import com.comdo.newup_loan.util.StringUtils;
import com.comdo.newup_loan.util.TitleMenuUtil;
import com.liji.takephoto.Constatnt;
import com.liji.takephoto.IMakePic;
import com.liji.takephoto.MakePicAdapter;
import com.liji.takephoto.OnImageUploadListener;
import com.liji.takephoto.PhotoInfo;
import com.liji.takephoto.TakePhoto;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


/**
 * Created by liyuan on 2017/11/6.
 */

public class XudaiApplyActivity extends BaseActivity<XudaiApplyPersenter> implements View.OnClickListener, XudaiApplyContact.View, IMakePic {
    @BindView(R.id.btn_sumbit)
    Button mSubmitBtn;
    @BindView(R.id.content)
    LinearLayout mLlAddID;
    @BindView(R.id.tv_tip)
    TextView mTipTextView;
    @BindView(R.id.tv_recharge)
    TextView mRechargeTextView;

    @BindView(R.id.ed_percent)
    EditText mPercentEdit;
    @BindView(R.id.tv_yhbj)
    TextView yhbjText;
    @BindView(R.id.tv_yhlx)
    TextView yhlxText;
    @BindView(R.id.tv_yhglf)
    TextView yhglfText;
    @BindView(R.id.tv_fxj)
    TextView fxjText;
    @BindView(R.id.tv_gps)
    TextView gpsText;
    @BindView(R.id.tv_tcf)
    TextView tcfText;
    @BindView(R.id.tv_yhze)
    TextView yhzeText;
    @BindView(R.id.rv_photos)
    RecyclerView mPhotoRecyclerView;

    private String urls;
    //费率
    private String rate;
    private ToXuDaiApply toXuDaiApply;
    ArrayList<PhotoInfo> photoInfos = new ArrayList<>();
    ArrayList<UpLoadBean> photos = new ArrayList<>();
    StringBuffer sb = new StringBuffer();
    public static int position;
    public static String path;
    public static String compresspath;
    private MakePicAdapter mMakePicAdapter;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_repayment_xudai_apply;
    }

    @Override
    protected void init() {
        super.init();

    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        new TitleMenuUtil(XudaiApplyActivity.this, "续贷申请", true);
        mRechargeTextView.setOnClickListener(this);
        mTipTextView.setOnClickListener(this);
        mSubmitBtn.setOnClickListener(this);
        mPercentEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals(""))
                    return;
                if (Float.parseFloat(s.toString()) > 100)
                    mPercentEdit.setText(100 + "");

                mPresenter.getData(getIntent().getIntExtra("repayPlanId", 0), Config.loginInfo.getUserId(), mPercentEdit.getText().toString());
            }
        });
        initRecycleView();
        mPercentEdit.setText("5");
    }

    @Override
    public XudaiApplyPersenter getmPresenter() {
        return new XudaiApplyPersenter();
    }

    @Override
    public void presenterSetView() {
        if (mPresenter != null)
            mPresenter.setView(this);
    }

    @Override
    public void getFail(String failMessage) {
        showToast(failMessage);
    }

    @Override
    public void getData(ToXuDaiApply datas) {
        rate = mPercentEdit.getText().toString();
        toXuDaiApply = datas;
        //应还本金
        yhbjText.setText(StringUtils.getMoneyString(datas.getPrinciple()));
        //应还利息
        yhlxText.setText(StringUtils.getMoneyString(datas.getSqdjCost()));
        //应还管理费
        yhglfText.setText(StringUtils.getMoneyString(datas.getManageCost()));
        //应还风险金
        fxjText.setText(StringUtils.getMoneyString(datas.getRiskCost()));
        //应还gps使用费
        gpsText.setText(StringUtils.getMoneyString(datas.getGpsUseCost()));
        //应还停车费
        tcfText.setText(StringUtils.getMoneyString(datas.getCarStopCost()));
        //应还总额
        yhzeText.setText(StringUtils.getMoneyString(datas.getTotalPay()));
        photoInfos.clear();
        for(UpLoadBean bean:datas.getPicUrls()){
            PhotoInfo photo=new PhotoInfo();
            photo.setImgUrl(Config.PIC_FORE+bean.getUrl());
            photo.setUid(bean.getImgId()+"");
            photoInfos.add(photo);
        }
        photos.clear();;
        photos.addAll(datas.getPicUrls());
        mMakePicAdapter.notifyDataSetChanged();;
    }

    @Override
    public void upLoad(UpLoadBean result) {
        Log.e("upLoad", result.getUrl());
        showInfo(position, path, compresspath,result.getUrl());
        photos.add(result);
        //photoInfos.get(position).setImgUrl(Config.PIC_FORE+result.getUrl());
    }

    //提交续贷申请成功
    @Override
    public void goOnLoanApply(String result) {
        showToast("提交续贷申请成功!");
        finish();
    }

    @Override
    public void getTip(String tip) {
        getDialog(tip);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_sumbit:
                sumbit();
                break;
            case R.id.tv_recharge:
                Intent intent = new Intent(XudaiApplyActivity.this, MineTopUpActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_tip:
                mPresenter.getTip();
                break;
        }
    }

    private void getDialog(String string) {
        AlertDialog.Builder builder = new AlertDialog.Builder(XudaiApplyActivity.this);
        //builder.setIcon(R.drawable.ic_launcher);
        builder.setTitle("注意事项");
        builder.setMessage(Html.fromHtml(string));
        //    设置一个PositiveButton
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }

    private void sumbit() {
        if (StringUtils.isNull(rate) || toXuDaiApply == null) {
            showToast("请填写本金比列!");
            return;
        }
        if (Float.parseFloat(rate) < 5) {
            showToast("本金比列不能小于5!");
            return;
        }
        urls = "";
        if (photoInfos.size() != 0) {
            for (int i = 0; i < photoInfos.size(); i++) {
                if (!(i == photoInfos.size() - 1)) {
                    urls = urls + photoInfos.get(i).getImgUrl() + ",";
                } else {
                    urls = urls + photoInfos.get(i).getImgUrl();
                }
            }
        }
        mPresenter.goOnLoanApply(getIntent().getIntExtra("repayPlanId", 0), Config.loginInfo.getUserId(), rate, toXuDaiApply, urls);
    }

    private void initRecycleView() {
        GridLayoutManager layoutManager = new GridLayoutManager(XudaiApplyActivity.this, 4);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mPhotoRecyclerView.setLayoutManager(layoutManager);
        mMakePicAdapter = new MakePicAdapter(XudaiApplyActivity.this, photoInfos, XudaiApplyActivity.this, Constatnt.EDIT);
        mPhotoRecyclerView.setAdapter(mMakePicAdapter);

    }

    OnImageUploadListener mImageUploadListener;

    @Override
    public void setPicUploadListener(OnImageUploadListener onImageUploadListener) {
        this.mImageUploadListener = onImageUploadListener;
    }

    @Override
    public void takePic(final int position) {
        Log.e("ssc", "ssc+" + position);
        if (position > 7) {
            showToast("最多只能提交8张图片！");
            return;
        }
        TakePhoto takePhoto = new TakePhoto(XudaiApplyActivity.this);
        takePhoto.setOnPictureSelected(new TakePhoto.onPictureSelected() {
            @Override
            public void select(String path, String compresspath) {
                mPresenter.upLoad(Config.loginInfo.getUserId(), compresspath, getIntent().getIntExtra("repayPlanId", 0));
                XudaiApplyActivity.position = position;
                XudaiApplyActivity.path = path;
                XudaiApplyActivity.compresspath = compresspath;
            }
        });
        takePhoto.show();
    }

    @Override
    public void delPic(String url) {
        Log.e("delPic", url);
        mPresenter.delImg(Config.loginInfo.getUserId(),findPosition(url));

    }

    private int findPosition(String url) {
        int id=0;
       for(UpLoadBean bean:photos){

           if(url.equals(Config.PIC_FORE+bean.getUrl()))
               id=bean.getImgId();
       }
        return id;
    }

    @Override
    public void delImg(String result) {
        showToast(result);
    }

    @Override
    public void delImgFail(String result) {
        showToast(result);
        mPresenter.getData(getIntent().getIntExtra("repayPlanId", 0), Config.loginInfo.getUserId(), mPercentEdit.getText().toString());
    }

    /**
     * @param position
     * @param path
     * @param compresspath
     */
    private void showInfo(int position, String path, String compresspath,String UrlPath) {

        sb.append("原始的大小：" + new File(path).length() / 1024 + " k");
        sb.append("   ");
        sb.append("原始路径：" + path);

        sb.append("\n");

        sb.append("压缩后大小：" + new File(compresspath).length() / 1024 + " k");
        sb.append("   ");
        sb.append("压缩路径：" + compresspath + "\n");

        List<PhotoInfo> photoInfos = new ArrayList<>();
        PhotoInfo photoInfo = new PhotoInfo();
       // photoInfo.setCompressPath(path);
       // photoInfo.setOriginalPath(compresspath);
        photoInfo.setImgUrl(Config.PIC_FORE+UrlPath);
        photoInfos.add(photoInfo);

        if (null != mImageUploadListener) {
            XudaiApplyActivity.this.mImageUploadListener.onImageUploadList(photoInfos);
        }
        Log.d("takephotolib", "" + sb.toString());
    }


}
